package cn.iocoder.yudao.module.bill.service.bill_cate;

import cn.iocoder.yudao.module.bill.controller.admin.common.CategoryNode;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.bill.controller.admin.bill_cate.vo.*;
import cn.iocoder.yudao.module.bill.dal.dataobject.bill_cate.BillCateDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.bill.dal.mysql.bill_cate.BillCateMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bill.enums.ErrorCodeConstants.*;

/**
 * 账单分类 Service 实现类
 *
 * @author mmciel
 */
@Service
@Validated
public class BillCateServiceImpl implements BillCateService {

    @Resource
    private BillCateMapper cateMapper;

    @Override
    public Long createCate(BillCateSaveReqVO createReqVO) {
        // 校验父ID的有效性
        validateParentCate(null, createReqVO.getParentId());
        // 校验分类的唯一性
        validateCateClsNameUnique(null, createReqVO.getParentId(), createReqVO.getClsName());

        // 插入
        BillCateDO cate = BeanUtils.toBean(createReqVO, BillCateDO.class);
        cateMapper.insert(cate);
        // 返回
        return cate.getId();
    }

    @Override
    public void updateCate(BillCateSaveReqVO updateReqVO) {
        // 校验存在
        validateCateExists(updateReqVO.getId());
        // 校验父ID的有效性
        validateParentCate(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验分类的唯一性
        validateCateClsNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getClsName());

        // 更新
        BillCateDO updateObj = BeanUtils.toBean(updateReqVO, BillCateDO.class);
        cateMapper.updateById(updateObj);
    }

    @Override
    public void deleteCate(Long id) {
        // 校验存在
        validateCateExists(id);
        // 校验是否有子账单分类
        if (cateMapper.selectCountByParentId(id) > 0) {
            throw exception(CATE_EXITS_CHILDREN);
        }
        // 删除
        cateMapper.deleteById(id);
    }

    private void validateCateExists(Long id) {
        if (cateMapper.selectById(id) == null) {
            throw exception(CATE_NOT_EXISTS);
        }
    }

    private void validateParentCate(Long id, Long parentId) {
        if (parentId == null || BillCateDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父账单分类
        if (Objects.equals(id, parentId)) {
            throw exception(CATE_PARENT_ERROR);
        }
        // 2. 父账单分类不存在
        BillCateDO parentCate = cateMapper.selectById(parentId);
        if (parentCate == null) {
            throw exception(CATE_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父账单分类，如果父账单分类是自己的子账单分类，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentCate.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(CATE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父账单分类
            if (parentId == null || BillCateDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentCate = cateMapper.selectById(parentId);
            if (parentCate == null) {
                break;
            }
        }
    }

    private void validateCateClsNameUnique(Long id, Long parentId, String clsName) {
        BillCateDO cate = cateMapper.selectByParentIdAndClsName(parentId, clsName);
        if (cate == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的账单分类
        if (id == null) {
            throw exception(CATE_CLS_NAME_DUPLICATE);
        }
        if (!Objects.equals(cate.getId(), id)) {
            throw exception(CATE_CLS_NAME_DUPLICATE);
        }
    }

    @Override
    public BillCateDO getCate(Long id) {
        return cateMapper.selectById(id);
    }

    @Override
    public List<BillCateDO> getCateList(BillCateListReqVO listReqVO) {
        return cateMapper.selectList(listReqVO);
    }

    @Override
    public List<CategoryNode> getCateTree() {

        List<BillCateTreeRespVO> categories = cateMapper.getCateTree();

        Map<String, CategoryNode> parentMap = new HashMap<>();

        for (BillCateTreeRespVO category : categories) {
            String amountType = category.getAmountType();
            String clsName = category.getClsName();
            String subClsName = category.getSubClsName();

            // Create or get the parent node
            CategoryNode parentNode = parentMap.computeIfAbsent(amountType, k -> {
                CategoryNode node = new CategoryNode();
                node.setValue(amountType);
                node.setLabel(amountType);
                node.setChildren(new ArrayList<>());
                return node;
            });

            // Create or get the child node
            CategoryNode childNode = parentNode.getChildren().stream()
                    .filter(node -> node.getValue().equals(clsName))
                    .findFirst()
                    .orElseGet(() -> {
                        CategoryNode node = new CategoryNode();
                        node.setValue(clsName);
                        node.setLabel(clsName);
                        node.setChildren(new ArrayList<>());
                        parentNode.getChildren().add(node);
                        return node;
                    });

            // Add the sub-category to the child node
            CategoryNode subNode = new CategoryNode();
            subNode.setValue(subClsName);
            subNode.setLabel(subClsName);
            childNode.getChildren().add(subNode);
        }
        return new ArrayList<>(parentMap.values());
    }

}